/**
 * 成绩管理相关API
 */
import { get, post, put, del } from './index'
import type {
  ApiResponse,
  PaginatedResponse,
  PaginationParams,
  GradeSheet,
  Grade,
  Examination,
  Question,
  User
} from '@/types'

// 成绩单管理
export const getGradeSheets = (params?: PaginationParams & {
  examination?: number
  student?: number
  teacher?: number
  status?: string
}) => {
  return get<ApiResponse<PaginatedResponse<GradeSheet>>>('/api/v1/grading/grade-sheets/', params)
}

export const getGradeSheet = (id: number) => {
  return get<ApiResponse<GradeSheet>>(`/api/v1/grading/grade-sheets/${id}/`)
}

export const createGradeSheet = (data: {
  examination: number
  student: number
  status: string
  total_score?: number
  passing_score?: number
}) => {
  return post<ApiResponse<GradeSheet>>('/api/v1/grading/grade-sheets/', data)
}

export const updateGradeSheet = (id: number, data: Partial<GradeSheet>) => {
  return put<ApiResponse<GradeSheet>>(`/api/v1/grading/grade-sheets/${id}/`, data)
}

export const deleteGradeSheet = (id: number) => {
  return del(`/api/v1/grading/grade-sheets/${id}/`)
}

// 成绩管理
export const getGrades = (params?: PaginationParams & {
  grade_sheet?: number
  question?: number
  score__gte?: number
  score__lte?: number
}) => {
  return get<ApiResponse<PaginatedResponse<Grade>>>('/api/v1/grading/grades/', params)
}

export const createGrade = (data: {
  grade_sheet: number
  question: number
  score: number
  max_score: number
  feedback?: string
  is_auto_graded: boolean
}) => {
  return post<ApiResponse<Grade>>('/api/v1/grading/grades/', data)
}

export const updateGrade = (id: number, data: Partial<Grade>) => {
  return put<ApiResponse<Grade>>(`/api/v1/grading/grades/${id}/`, data)
}

export const deleteGrade = (id: number) => {
  return del(`/api/v1/grading/grades/${id}/`)
}

export const batchCreateGrades = (gradeSheetId: number, grades: {
  question: number
  score: number
  max_score: number
  feedback?: string
}[]) => {
  return post<ApiResponse<Grade[]>>(
    `/api/v1/grading/grade-sheets/${gradeSheetId}/batch-create-grades/`,
    { grades }
  )
}

// 自动阅卷
export const autoGradeExam = (examId: number) => {
  return post<ApiResponse<{
    total_students: number
    graded_count: number
    failed_count: number
    errors: string[]
  }>>(`/api/v1/grading/auto-grade/${examId}/`)
}

export const autoGradeQuestion = (examId: number, questionId: number) => {
  return post<ApiResponse<Grade[]>>(
    `/api/v1/grading/auto-grade/${examId}/question/${questionId}/`
  )
}

// 成绩统计
export const getGradeStatistics = (params?: {
  examination?: number
  teacher?: number
  class_id?: number
  start_date?: string
  end_date?: string
}) => {
  const queryParams = new URLSearchParams()
  Object.entries(params || {}).forEach(([key, value]) => {
    if (value) queryParams.append(key, String(value))
  })

  const query = queryParams.toString()
  const url = query ? `/api/v1/grading/statistics/?${query}` : '/api/v1/grading/statistics/'

  return get<ApiResponse<{
    total_exams: number
    total_students: number
    average_score: number
    pass_rate: number
    grade_distribution: {
      excellent: number
      good: number
      pass: number
      fail: number
    }
    recent_trends: Array<{
      date: string
      average_score: number
      pass_rate: number
    }>
  }>>(url)
}

// 成绩分析
export const getGradeAnalysis = (examinationId: number) => {
  return get<ApiResponse<{
    exam: Examination
    statistics: {
      total_students: number
      average_score: number
      median_score: number
      std_deviation: number
      highest_score: number
      lowest_score: number
      pass_rate: number
    }
    score_distribution: Array<{
      range: string
      count: number
      percentage: number
    }>
    question_analysis: Array<{
      question: Question
      average_score: number
      max_score: number
      correct_rate: number
      difficulty: string
    }>
    class_distribution: Array<{
      class_name: string
      average_score: number
      pass_rate: number
      student_count: number
    }>
  }>>(`/api/v1/grading/analysis/${examinationId}/`)
}

// 成绩发布
export const publishGrades = (examinationId: number) => {
  return post<ApiResponse<Examination>>(`/api/v1/grading/examinations/${examinationId}/publish-grades/`)
}

export const unpublishGrades = (examinationId: number) => {
  return post<ApiResponse<Examination>>(`/api/v1/grading/examinations/${examinationId}/unpublish-grades/`)
}

// 成绩导出
export const exportGrades = (params: {
  examination?: number
  format: 'excel' | 'csv' | 'pdf'
  class_id?: number
}) => {
  return get(`/api/v1/grading/export-grades/`, params, {
    responseType: 'blob'
  })
}

export const exportGradeSheet = (gradeSheetId: number, format: 'pdf' | 'excel') => {
  return get(`/api/v1/grading/grade-sheets/${gradeSheetId}/export/`, {
    format
  }, {
    responseType: 'blob'
  })
}

// 学生成绩查询
export const getStudentGrades = (studentId: number, params?: PaginationParams) => {
  return get<ApiResponse<PaginatedResponse<GradeSheet>>>(
    `/api/v1/grading/students/${studentId}/grades/`,
    params
  )
}

export const getStudentGradeTrends = (studentId: number, params?: {
  subject?: string
  start_date?: string
  end_date?: string
}) => {
  const queryParams = new URLSearchParams()
  Object.entries(params || {}).forEach(([key, value]) => {
    if (value) queryParams.append(key, String(value))
  })

  const query = queryParams.toString()
  const url = query
    ? `/api/v1/grading/students/${studentId}/trends/?${query}`
    : `/api/v1/grading/students/${studentId}/trends/`

  return get<ApiResponse<Array<{
    examination: Examination
    grade_sheet: GradeSheet
    rank: number
    percentile: number
  }>>>(url)
}

// 教师成绩查看
export const getTeacherGrades = (teacherId: number, params?: PaginationParams) => {
  return get<ApiResponse<PaginatedResponse<GradeSheet>>>(
    `/api/v1/grading/teachers/${teacherId}/grades/`,
    params
  )
}

// 成绩单打印
export const printGradeSheet = (gradeSheetId: number) => {
  return get<ApiResponse<{
    html_content: string
    css_styles: string
  }>>(`/api/v1/grading/grade-sheets/${gradeSheetId}/print/`)
}

// 批量操作
export const batchPublishGrades = (examinationIds: number[]) => {
  return post<ApiResponse<{
    success_count: number
    failed_count: number
    failed_ids: number[]
  }>>('/api/v1/grading/batch-publish-grades/', {
    examination_ids: examinationIds
  })
}

export const batchExportGradeSheets = (gradeSheetIds: number[], format: 'excel' | 'pdf') => {
  return post('/api/v1/grading/batch-export-grade-sheets/', {
    grade_sheet_ids: gradeSheetIds,
    format
  }, {
    responseType: 'blob'
  })
}

// AI阅卷辅助
export const getAIGradingSuggestion = (gradeId: number) => {
  return get<ApiResponse<{
    suggested_score: number
    confidence: number
    reasoning: string
    improvement_suggestions: string[]
  }>>(`/api/v1/grading/grades/${gradeId}/ai-suggestion/`)
}

export const applyAIGradingSuggestion = (gradeId: number) => {
  return post<ApiResponse<Grade>>(`/api/v1/grading/grades/${gradeId}/apply-ai-suggestion/`)
}

// 成绩单审核和发布
export const publishGradeSheet = (gradeSheetId: number) => {
  return post<ApiResponse<GradeSheet>>(`/api/v1/grading/grade-sheets/${gradeSheetId}/publish/`)
}

export const reviewGradeSheet = (gradeSheetId: number, data: {
  approved: boolean
  feedback?: string
}) => {
  return post<ApiResponse<GradeSheet>>(`/api/v1/grading/grade-sheets/${gradeSheetId}/review/`, data)
}

// 成绩计算
export const calculateGrades = (examinationId: number) => {
  return post<ApiResponse<{
    success_count: number
    failed_count: number
    errors: string[]
  }>>(`/api/v1/grading/calculate-grades/${examinationId}/`)
}

// 导出统一的成绩管理API对象
export const gradingApi = {
  // 成绩单管理
  getGradeSheets,
  getGradeSheet,
  createGradeSheet,
  updateGradeSheet,
  deleteGradeSheet,

  // 成绩管理
  getGrades,
  createGrade,
  updateGrade,
  deleteGrade,
  batchCreateGrades,

  // 自动阅卷
  autoGradeExam,
  autoGradeQuestion,

  // 成绩统计和分析
  getGradeStatistics,
  getGradeAnalysis,

  // 成绩发布
  publishGrades,
  unpublishGrades,
  publishGradeSheet,
  reviewGradeSheet,
  calculateGrades,

  // 成绩导出
  exportGrades,
  exportGradeSheet,
  printGradeSheet,

  // 查询接口
  getStudentGrades,
  getStudentGradeTrends,
  getTeacherGrades,

  // 批量操作
  batchPublishGrades,
  batchExportGradeSheets,

  // AI阅卷辅助
  getAIGradingSuggestion,
  applyAIGradingSuggestion
}
